const ApiErrorNames = require('../config/ApiErrorNames');
const APIError = require('./result').APIError;

/**
 * access_token验证中间件
 */

const whiteUrl = [
  '/api/user/login',
  '/api/user/regist',
];
const whiteUrlReg = /\/api\/auth\/*/;
let authToken = async (ctx, next) => {
  // 用户登录或者不是api请求时，不用验证
  if (whiteUrl.includes(ctx.url)) {
    return await next();
  } else if (whiteUrlReg.test(ctx.url)) {
    let token = ctx.session.user;
    if (!token) {
      throw new APIError(ApiErrorNames.TOKEN_NOT_FOUND);
    }
  }
  await next();
};

module.exports = authToken;
